//
//  UIView+JKExtension.swift
//  JKFramework-Swift
//
//  Created by albert on 2017/11/27.
//  Copyright © 2017年 安永博. All rights reserved.
//

import UIKit

// 定义关联的key
private let jk_bottomSafeAreaView_key = "jk_bottomSafeAreaView_key"

public extension UIView {
    
    /** 尺寸 */
    var size : CGSize {
        set {
            var frame = self.frame
            frame.size = newValue
            self.frame = frame
        }
        
        get {
            return self.frame.size
        }
    }
    
    /** 宽度 */
    var width : CGFloat {
        set {
            var frame = self.frame
            frame.size.width = newValue
            self.frame = frame
        }
        
        get {
            return self.frame.size.width
        }
    }
    
    /** 高度 */
    var height : CGFloat {
        set {
            var frame = self.frame
            frame.size.height = newValue
            self.frame = frame
        }
        
        get {
            return self.frame.size.height
        }
    }
    
    /** origin */
    var origin : CGPoint {
        set {
            var frame = self.frame
            frame.origin = newValue
            self.frame = frame
        }
        
        get {
            return self.frame.origin
        }
    }
    
    /** X */
    var x : CGFloat {
        set {
            var frame = self.frame
            frame.origin.x = newValue
            self.frame = frame
        }
        
        get {
            return self.frame.origin.x
        }
    }
    
    /** Y */
    var y : CGFloat {
        set {
            var frame = self.frame
            frame.origin.y = newValue
            self.frame = frame
        }
        
        get {
            return self.frame.origin.y
        }
    }
    
    /** maxX */
    var maxX : CGFloat {
        set {
            var frame = self.frame
            frame.origin.x = newValue - frame.size.width
            self.frame = frame
        }
        
        get {
            return self.frame.maxX
        }
    }
    
    /** maxY */
    var maxY : CGFloat {
        set {
            var frame = self.frame
            frame.origin.y = newValue - frame.size.height
            self.frame = frame
        }
        
        get {
            return self.frame.maxY
        }
    }
    
    /** centerX */
    var centerX : CGFloat {
        set {
            var center = self.center
            center.x = newValue
            self.center = center
        }
        
        get {
            return self.center.x
        }
    }
    
    /** centerY */
    var centerY : CGFloat {
        set {
            var center = self.center
            center.y = newValue
            self.center = center
        }
        
        get {
            return self.center.y
        }
    }
    
    //    struct RuntimeKey {
    //        static let jk_bottomSafeAreaView_key = UnsafeRawPointer.init(bitPattern: "jk_bottomSafeAreaView_key".hashValue)
    //    }
    
    /** jk_bottomSafeAreaView */
    var jk_bottomSafeAreaView : UIView? {
        set {
            objc_setAssociatedObject(self, jk_bottomSafeAreaView_key, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
        
        get {
            return  objc_getAssociatedObject(self, jk_bottomSafeAreaView_key) as? UIView
        }
    }
    
    /** 适配iPhone X底部安全区域，如果设备并非iPhone X，则不会创建jk_bottomSafeAreaView */
    func jk_adaptBottomSafeArea(){
        if UIApplication.shared.statusBarFrame.size.height < 44 {
            return;
        }
        
        if self.jk_bottomSafeAreaView != nil {
            return;
        }
        
        let bottomSafeAreaView = UIView(frame: CGRect(x: 0, y: UIApplication.shared.statusBarFrame.size.height - 34, width: UIApplication.shared.statusBarFrame.size.width, height: 34))
        addSubview(bottomSafeAreaView)
        self.jk_bottomSafeAreaView = bottomSafeAreaView
    }
    
    /** 适配iOS11的scrollView */
    func jk_adapt_iOS_11_scrollView(){
        
        if !(self is UIScrollView) {
            return;
        }
        
        let selector = NSSelectorFromString("setContentInsetAdjustmentBehavior:")
        
        if self.responds(to: selector) {
            
            (self as! UIScrollView).perform(selector, with: 2)
        }
    }
    
    func jk_copyView() -> Any?{
        
        return NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: self))
    }
    
    /** 切圆角 */
    func jk_clipRound(radius:CGFloat, corner:UIRectCorner, borderWidth:CGFloat, borderColor:UIColor?){
        
        let path = UIBezierPath(roundedRect: self.bounds,
                                byRoundingCorners: corner,
                                cornerRadii: CGSize(width: radius, height: radius))
        
        if radius > 0 {
            
            let shapeLayer = CAShapeLayer()
            shapeLayer.path = path.cgPath
            self.layer.mask = shapeLayer
        }
        
        if (borderWidth <= 0 || borderColor != nil) {return}
        
        let borderLayer = CAShapeLayer()
        
        var path2 : UIBezierPath? = nil
        
        if (radius <= 0) {
            path2 = UIBezierPath(rect: CGRect(x: borderWidth,
                                              y: borderWidth,
                                              width: self.bounds.size.width - borderWidth * 2,
                                              height: self.bounds.size.height - borderWidth * 2))
        }
        
        borderLayer.path = (radius <= 0) ? path2?.cgPath : path.cgPath
        borderLayer.lineWidth = borderWidth * 2
        borderLayer.strokeColor = borderColor?.cgColor
        borderLayer.fillColor = nil
        
        self.layer.addSublayer(borderLayer)
    }
    
    /** 判断控件是否真正显示在窗口范围内 */
    func jk_isShowingOnKeyWindow() -> Bool{
        //主窗口
        let keyWindow = UIApplication.shared.delegate?.window
        
        //得到self在主窗口中的frame
        // 转换self的frame，写成nil就是转为以屏幕左上角为原点
        //CGRect newFrame = [self.superview convertRect:subview.frame toView:nil];
        let newFrame = keyWindow??.convert(self.frame, from: self.superview)
        
        //窗口的bounds
        let windowBounds = keyWindow??.bounds
        
        //主窗口的bounds 和 subview主窗口左上角为原点的frame 是否有重叠
        // CGRectIntersectsRect(newFrame, windowBounds)比较两个rect是否有交叉
        let intersects = newFrame?.intersects(windowBounds!)//CGRectIntersectsRect(newFrame, windowBounds);
        
        //返回。控件没有被添加到窗口上时，控件的window == nil
        return (!self.isHidden) && (self.alpha > 0.01) && (intersects!) && (self.window?.isEqual(keyWindow as Any))!;
    }
    
    /** 从xib中加载view */
    class func jk_viewFromXib() -> UIView{
        return Bundle.main.loadNibNamed(NSStringFromClass(self), owner: nil, options: nil)?.last as! UIView// [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self) owner:nil options:nil] lastObject];
    }
    
    /** 切换横竖屏 */
    //    class func jk_changeInterfaceOrientation(orientation : UIInterfaceOrientation) {
    //
    //        let selector = NSSelectorFromString("setOrientation:")
    //
    //        if UIDevice.current.responds(to: selector) {
    //            let invocation = NSInvocation//[NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
    //            [invocation setSelector:selector];
    //            [invocation setTarget:[UIDevice currentDevice]];
    //            int val                  = orientation;
    //            [invocation setArgument:&val atIndex:2];
    //            [invocation invoke];
    //        }
    //    }
    
    /** 获取一个view所属的控制器 */
    func jk_getViewController() -> UIViewController? {
        
        var next = self.next
        
        while next != nil {
            
            if next is UIViewController {
                
                return next as? UIViewController
            }
            
            next = next?.next
        }
        
        return nil
    }
    
    /** 使用layer加一条线之类 */
    func jk_addLine(frame:CGRect, color:UIColor) {
        
        let layer = CALayer()
        
        layer.frame = frame
        layer.backgroundColor = color.cgColor
        
        self.layer.addSublayer(layer)
    }
    
    /** 全局隐藏键盘 */
    class func JKHideKeyboard() {
        
        UIApplication.shared.delegate?.window??.endEditing(true)
    }
    
}



